package sess

import (
	"fmt"
	"net"

	"gitee.com/night-tc/gobige/global"
	"github.com/xtaci/kcp-go"
	"golang.org/x/net/netutil"
)

/*
实现连接逻辑的包
*/

func GetListener(protocal string, info *global.ListenCfg) (result net.Listener, port int) {
	var err error
	for port = info.PortMin; port <= info.PortMax; port++ {
		switch protocal {
		case "tcp":
			result, err = net.Listen("tcp",
				fmt.Sprintf("%s:%d", info.Listen, port))
		case "kcp":
			result, err = kcp.Listen(fmt.Sprintf("%s:%d", info.Listen, port))
		default:
			panic("WRONG PROTOCAL")
		}
		if err == nil {
			break
		}
	}
	if err != nil {
		panic(err)
	}
	if info.MaxConn > 0 {
		result = netutil.LimitListener(result, info.MaxConn)
	}
	return
}

type IkcpSession interface {
	// SetStreamMode toggles the stream mode on/off
	SetStreamMode(enable bool)
	// SetWindowSize set maximum window size
	SetWindowSize(sndwnd, rcvwnd int)

	// SetNoDelay calls nodelay() of kcp
	// https://github.com/skywind3000/kcp/blob/master/README.en.md#protocol-configuration
	SetNoDelay(nodelay, interval, resend, nc int)
	// SetDSCP sets the 6bit DSCP field in IPv4 header, or 8bit Traffic Class in IPv6 header.
	//
	// if the underlying connection has implemented `func SetDSCP(int) error`, SetDSCP() will invoke
	// this function instead.
	//
	// It has no effect if it's accepted from Listener.
	SetDSCP(dscp int) error
	// SetMtu sets the maximum transmission unit(not including UDP header)
	SetMtu(mtu int) bool
	// SetACKNoDelay changes ack flush option, set true to flush ack immediately,
	SetACKNoDelay(nodelay bool)
}

const (
	// 压缩标记
	SessFlag_Compress = 1 << iota
	// 加密标记
	SessFlag_Encrypt
)
